/**
 * @method 打包工具
 * @author Lkx
 * @create 2020.06.27
 * @update 2021.01.02
 */

const gulp    = require("gulp");
const connect = require("gulp-connect");

// 文件打包前缀说明
const pac  = require("./package.json");
const note_build = `/**\n * @method Kxui\n * @author Lkx\n * @create ${pac.createTime}\n * @update ${pac.updateTime}\n * @website https://lkx2217.gitee.io/kxuidocs\n * @version ${pac.version}\n * @released under the MIT License\n */\n\n`;
const note_copy = `/**\n * @method Kxui\n * @author third party module\n * @update ${pac.updateTime}\n * @website https://lkx2217.gitee.io/kxuidocs\n * @released under the MIT License\n */\n\n`;

// 本地服务监听文件
// 打包遍历存放路径
const path_dist = ["./dist/"];
const path_dist_base = "./src/components";

// 开发构建目录
const path_html = ["./src/views/index.html"];
const path_javascript = ["./src/components/*.js", "./src/components/modules/built/*.js", "./src/components/modules/third/*.js"];

// 打包构建目录
const path_build = ["./src/components/*.js", "./src/components/modules/built/*.js"];
const path_copy = ["./src/components/modules/third/*.js"];

// 用于不同环境
let is_serve = false;

// dist 文件清理
// 在构建代码或在打包代码时，均先清空 dist 文件夹
const gulp_del = require("del");
gulp.task("del", () => {
  return gulp_del([
    "./dist/**"
  ]);
});

// 代码实时监听
gulp.task("html", () => {
  return gulp.src(path_html).pipe(connect.reload());
});

// 代码实时监听
// 进行代码转 ES5 格式
// 进行代码压缩，减小体积
const gulp_babel  = require("gulp-babel");
const gulp_uglify = require("gulp-uglify");
const gulp_header = require("gulp-header");
gulp.task("javascript", () => {
  if (is_serve) {
    return gulp.src(path_javascript).pipe(connect.reload());
  } else {
    return gulp.src(path_build, { base: path_dist_base })
      .pipe(gulp_babel())
      .pipe(gulp_uglify())
      .pipe(gulp_header(note_build))
      .pipe(gulp.dest(path_dist));
  }
});

// 其他模块代码复制
gulp.task("copy", () => {
  return gulp.src(path_copy, { base: path_dist_base })
    .pipe(gulp_header(note_copy))
    .pipe(gulp.dest(path_dist));
});

// 开发代码实时监听
// 监听 HTML 代码实时变化
// 监听 JAVASCRIPT 代码实时变化
const gulp_watch = require("gulp-watch");
gulp.task("watch", () => {
  gulp_watch(path_html, gulp.series("html"));
  gulp_watch(path_javascript, gulp.series("javascript"));
});

// 启动本地服务器
// 根据常量 path_html 进行主要文件访问
gulp.task("server", () => {
  is_serve = true;
  connect.server({
    root: "./",
    host: "0.0.0.0",
    index: path_html,
    livereload: true,
    port: 8000
  });
});

// 快捷命令行
// serve:启动本地服务器
// build:打包发行代码
gulp.task("serve", gulp.parallel("server", "watch"));
gulp.task("build", gulp.series("del", "javascript", "copy"));
